package com.hhj.king.invoker.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.netflix.appinfo.InstanceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author KING
 * @date 2018/9/22 18:25
 */
@RestController
@Slf4j
public class InvokerController {

    @Value("${hello.king:你好啊}")
    private String hello;
    private static JSONObject jsonObject = new JSONObject() {
        {
            put("success", false);
            put("data", "");
            put("code", 501);
            put("msg", "请求超时!");
        }
    };

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;


    @RequestMapping(value = "/hello")
    public String sayHello() {
        return "你好" + hello;
    }

    @RequestMapping(value = "/router")
    public String router() {
        String str;
        try {
            str = restTemplate.getForObject("http://first-provider/person/10086", String.class);
        } catch (Exception e) {
            log.error("远程调用失败!", e);
            str = jsonObject.toString();
        }
        return str;
    }

    @RequestMapping(value = "/router2")
    public String router2() {
        String str = "";
        List<ServiceInstance> list = getServiceInstace();
        for (ServiceInstance serviceInstance : list) {
            EurekaDiscoveryClient.EurekaServiceInstance eurekaServerIdentity = (EurekaDiscoveryClient.EurekaServiceInstance) serviceInstance;
            InstanceInfo instanceInfo = eurekaServerIdentity.getInstanceInfo();
            String str1 = (instanceInfo.getAppName() + "---" + instanceInfo.getInstanceId() + "---" + instanceInfo.getStatus()) + "+++";
            log.info(str1);
            str += str1;
        }
        return str;
    }

    private List<ServiceInstance> getServiceInstace() {
        List<ServiceInstance> reslist = new ArrayList<>();

        List<String> services = discoveryClient.getServices();
        for (String id : services) {
            List<ServiceInstance> list = discoveryClient.getInstances(id);
            reslist.addAll(list);

        }


        return reslist;
    }


}
